package com.etheart.lyric.htmlparser.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class HttpDownloader {
	
	private static final Log logger = LogFactory.getLog(HttpDownloader.class);
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		URL url = null;
		try {
			
			url = new URL(urlStr);
			System.out.println(url.getContent());
			System.out.println(url.getDefaultPort());
			
			
			System.out.println(url.getHost());
			System.out.println(url.getProtocol());
//			HttpURLConnection urlConn = (HttpURLConnection) url
//					.openConnection();
//			
//			buffer = new BufferedReader(new InputStreamReader(urlConn
//					.getInputStream()));
//			while ((line = buffer.readLine()) != null) {
//				sb.append(line);
//				System.out.println(line);
//			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public File download(String urlStr, String saveRealPath) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		
		byte[] buf = new byte[4096];
		try {
			
			int size = 0;
			// 建立链接
			url = new URL(urlStr);
			httpUrl = (HttpURLConnection) url.openConnection();
			// 连接指定的资源
			httpUrl.connect();
			// 获取网络输入流
			bis = new BufferedInputStream(httpUrl.getInputStream());
			// 建立文件
		
			fos = new FileOutputStream(saveRealPath);
			// 保存文件
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
		} catch (Exception e) {
			logger.error("文件下载失败," + url, e);
			return null;
		} finally {
			try {
				IOUtils.closeQuietly(fos);
				IOUtils.closeQuietly(bis);
				httpUrl.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return new File(saveRealPath);
	}

	public InputStream getInputStreamFromUrl(String urlStr,URL url)
			throws MalformedURLException, IOException {
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}
}
